package com.tmc.service.baseinfo;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tmc.bean.common.CommonResult;
import com.tmc.bean.common.ContextInfo;
import com.tmc.bean.common.Pagination;
import com.tmc.constant.CacheConstant;
import com.tmc.dao.impl.AirportDaoImpl;
import com.tmc.dao.impl.CityDaoImpl;
import com.tmc.dao.impl.CountryDaoImpl;
import com.tmc.entity.baseinfo.Airport;
import com.tmc.entity.baseinfo.City;
import com.tmc.entity.baseinfo.Country;
import com.tmc.service.cache.CacheServiceImpl;
import com.tmc.util.ObjectUtil;
import com.tmc.util.TxtUtil;

@Service
@Transactional
public class AirportServiceImpl {

	@Autowired
	private AirportDaoImpl airportDao;

	@Autowired
	private CityDaoImpl cityDao;

	@Autowired
	private CountryDaoImpl countryDao;
	
	@Autowired
	private CacheServiceImpl cache;
	
	private static String all_key = "KEY_AIRPORT_ALL";
	
	private static String map_key = "KEY_AIRPORT_ALL_MAP";

	private Log logger = LogFactory.getLog(this.getClass());

	public Pagination<Airport> findByCon(ContextInfo context, Airport cond, int pageIndex, int pageSize) {
		Pagination<Airport> result = airportDao.findAirportsByCon(context, cond, pageIndex, pageSize);
		this.setExtInfo(result);
		return result;
	}

	@Deprecated
	public List<Airport> findAll(ContextInfo context) {
		return airportDao.findAll();
	}
	
	public Airport getByCode(String code){
		if (ObjectUtil.noText(code)){
			return null;
		}
		Map<String, Airport> airports = this.findMapFromCache(null);
		return airports.get(code);
	}
	
	public String getNameByCode(String code){
		Airport bean = this.getByCode(code);
		if (bean == null){
			return "";
		}
		return bean.getAirportName();
	}
	
	public String getCityNameByCode(String code){
		Airport bean = this.getByCode(code);
		if (bean == null){
			return "";
		}
		return bean.getCityName();
	}
	
	public String getCityCodeByCode(String code){
		Airport bean = this.getByCode(code);
		if (bean == null){
			return "";
		}
		return bean.getCityCode();
	}
	
	public String getCountryCodeByCode(String code){
		Airport bean = this.getByCode(code);
		if (bean == null){
			return "";
		}
		return bean.getCountryCode();
	}
	
	@SuppressWarnings("unchecked")
	public List<Airport> findAllFromCache() {
		if (cache.get(CacheConstant.CACHE_NAME_600, all_key) != null) {
			return (List<Airport>) cache.get(CacheConstant.CACHE_NAME_600, all_key);
		}
		List<Airport> list = airportDao.findAll();
		cache.put(CacheConstant.CACHE_NAME_600, all_key, list);
		return list;
	}

	@SuppressWarnings("unchecked")
	public Map<String, Airport> findMapFromCache(ContextInfo context) {
		if (cache.get(CacheConstant.CACHE_NAME_600, map_key) != null) {
			return (Map<String, Airport>) cache.get(CacheConstant.CACHE_NAME_600, map_key);
		}
		Map<String, Airport> map = this.toMap(this.findAllFromCache());
		cache.put(CacheConstant.CACHE_NAME_600, map_key, map);
		return map;
	}

	private Map<String, Airport> toMap(List<Airport> airports) {
		Map<String, Airport> map = new HashMap<String, Airport>();
		for (Airport airport : airports) {
			map.put(airport.getAirportCode(), airport);
		}
		return map;
	}

	@CacheEvict(value = CacheConstant.CACHE_NAME_600, key = "'KEY_AIRPORT_ALL'")
	public CommonResult delete(ContextInfo context, Long airportId) {
		Airport airport = airportDao.getById(airportId);
		if (airport != null) {
			ObjectUtil.updateBaseInfo(airport, context);
			airport.setEnabledFlag("N");
			airportDao.update(airport);
		}
		return CommonResult.makeSuccess("删除成功！");
	}

	public Airport getById(ContextInfo context, Long airportId) {
		return airportDao.getById(airportId);
	}

	@CacheEvict(value = CacheConstant.CACHE_NAME_600, key = "'KEY_AIRPORT_ALL'")
	public CommonResult save(ContextInfo context, Airport airport) {
		CommonResult check = this.check(airport);
		if (!check.isSuccess()) {
			return check;
		}
		// 保存
		if (airport.getAirportId() == null) {
			ObjectUtil.setBaseInfo(airport, context);
			airportDao.insert(airport);
		} else {
			// 编辑
			try {
				Airport dbAirport = airportDao.getById(airport.getAirportId());
				if (dbAirport != null) {
					ObjectUtil.copyProperties(airport, dbAirport,
							new String[] { "createdBy", "creationDate", "airportId", "enabledFlag" });
				}
				// 根据城市三字码更新相关冗余字段
				if (ObjectUtil.hasText(dbAirport.getCityCode())){
					City city = cityDao.getByCode(context, dbAirport.getCityCode());
					if (city == null) {
						logger.error("无此城市！" + dbAirport.getCityCode());
						return CommonResult.makeFail("无此城市！" + dbAirport.getCityCode());
					}
					dbAirport.setCityName(city.getCityName());
					dbAirport.setCityNameEn(city.getCityNameEn());
					dbAirport.setCountryCode(city.getCountryCode());
					dbAirport.setCountryName(city.getCountryName());
					dbAirport.setCountryNameEn(city.getCountryNameEn());
					dbAirport.setContinentCode(city.getContinentCode());
					dbAirport.setContinentName(city.getContinentName());
					dbAirport.setContinentNameEn(city.getContinentNameEn());
				}
				ObjectUtil.updateBaseInfo(dbAirport, context);
				airportDao.update(dbAirport);
			} catch (Exception e) {
				logger.error("拷贝对象错误！", e);
				return CommonResult.makeFail("拷贝对象错误！");
			}
		}
		return CommonResult.makeSuccess();
	}

	private CommonResult check(Airport airport) {
		if (!ObjectUtil.hasText(airport.getAirportCode())) {
			return CommonResult.makeFail("机场三字码不能为空！");
		}
		if (!ObjectUtil.hasText(airport.getAirportName())) {
			return CommonResult.makeFail("机场名字不能为空！");
		}
		/*
		 * if (!ObjectUtil.hasText(airport.getCityCode())){ return
		 * CommonResult.makeFail("所属城市不能为空！"); }
		 */
		return CommonResult.makeSuccess();
	}

	private void setExtInfo(Pagination<Airport> result) {
		// TODO Auto-generated method stub

	}

	public void updateAll(ContextInfo context) {
		FileWriter fileWriter = null;
		try {
			// 这是读取文件修改机场名
			String[] datas = TxtUtil.get("C:/Users/legion/Desktop/airport_list/www.zhaobaojia.com/list_all.txt");
			fileWriter = new FileWriter("C:/Users/legion/Desktop/airport_list/www.zhaobaojia.com/list_ext.txt");
			// cityname airportcode countryname countrycode airportcode4
			// airportname airportnameen
			for (String data : datas) {
				System.out.println(data);
				String[] strs = data.split("/");
				Airport airport = airportDao.getByCode(context, strs[1]);
				String airportName = strs[5];
				if (ObjectUtil.hasText(airportName) && !airportName.contains("机场")) {
					airportName = airportName + "机场";
				}
				if (airport != null) {
					if (ObjectUtil.hasText(strs[0])) {
						airport.setCityName(strs[0]);
					}
					if (ObjectUtil.hasText(strs[2]) && ObjectUtil.hasText(strs[3])) {
						airport.setCountryName(strs[2]);
						airport.setCountryCode(strs[3]);
					}
					if (ObjectUtil.hasText(strs[5]) && !ObjectUtil.hasText(airport.getAirportName())) {
						airport.setAirportName(airportName);
					}
					System.out.println("更新" + airportName);
					airportDao.update(airport);
				} else {
					if (ObjectUtil.hasText(strs[0]) && ObjectUtil.hasText(strs[1]) && ObjectUtil.hasText(strs[5])) {
						Airport obj = new Airport();
						obj.setCityName(strs[0]);
						obj.setAirportCode(strs[1]);
						obj.setCountryName(strs[2]);
						obj.setCountryCode(strs[3]);
						obj.setAirportName(airportName);
						obj.setEnabledFlag("Y");
						airportDao.insert(obj);
					}
				}
			}
			// 这是把机场名不带机场二字的都还原
			/*
			 * List<Airport> allData = airportDao.findAll(context); for (Airport
			 * airport : allData){ if
			 * (ObjectUtil.hasText(airport.getAirportName()) &&
			 * !airport.getAirportName().contains("机场")){
			 * airport.setAirportName(""); airportDao.update(airport); } }
			 */
			// 这是把后面没有机场二字的加上机场二字
			/*
			 * List<Airport> allData = airportDao.findAll(context); for (Airport
			 * airport : allData){ if
			 * (ObjectUtil.hasText(airport.getAirportName()) &&
			 * !airport.getAirportName().contains("机场")){
			 * airport.setAirportName(airport.getAirportName() + "机场");
			 * airportDao.update(airport); } }
			 */
		} catch (Exception e) {
			logger.error(e);
		} finally {
			try {
				fileWriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println("处理完毕");
		}

	}

	public void updateUnAirport(ContextInfo context) {
		List<Airport> airports = airportDao.findAll();
		for (Airport airport : airports) {
			String airportCode = airport.getAirportCode();
			String cityCode = airport.getCityCode();
			String cityName = airport.getCityName();
			String countryName = airport.getCountryName();
			if (ObjectUtil.hasText(airportCode) && ObjectUtil.noText(cityCode) && ObjectUtil.hasText(cityName)
					&& ObjectUtil.hasText(countryName)) {
				// 失效机场
				airport.setEnabledFlag("N");
				ObjectUtil.updateBaseInfo(airport, context);
				airportDao.update(airport);
				// 新增城市
				City city = new City();
				city.setCityCode(airportCode);
				city.setCityName(cityName);
				city.setCountryName(countryName);
				city.setTimezone(airport.getTimezone());
				Country country = countryDao.getByName(context, countryName);
				if (country != null) {
					city.setCountryCode(country.getCountryCode());
					city.setCountryNameEn(country.getCountryNameEn());
					city.setContinentCode(country.getContinentCode());
					city.setContinentName(country.getContinentName());
					city.setContinentNameEn(country.getContinentNameEn());
				}
				ObjectUtil.setBaseInfo(city, context);
				System.out.println("新增城市" + cityName);
				cityDao.insert(city);
			}
		}
		System.out.println("处理完毕");

	}

	public void updateFromCity(ContextInfo context) {
		List<Airport> airports = airportDao.findAll();
		List<City> citys = cityDao.findAll(null);
		for (Airport airport : airports) {
			String cityCode = airport.getCityCode();
			for (City city : citys) {
				if(ObjectUtil.hasText(cityCode) && cityCode.equals(city.getCityCode())){
					airport.setCityName(city.getCityName());
					airport.setCityNameEn(city.getCityNameEn());
					airport.setCountryCode(city.getCountryCode());
					airport.setCountryName(city.getCountryName());
					airport.setCountryNameEn(city.getCountryNameEn());
					airport.setContinentName(city.getContinentName());
					airport.setContinentNameEn(city.getContinentNameEn());
					airport.setTimezone(city.getTimezone());
				}
			}
		}
		airportDao.update(airports);
		System.out.println("处理完毕");
	}

	public List<Airport> search4Text(String text) {
		text = text.toUpperCase();
		Map<String, Airport> map = this.findMapFromCache(null);
		List<Airport> airports = new ArrayList<Airport>();
		if (ObjectUtil.noText(text)) {
			airports.add(map.get("PVG"));
			airports.add(map.get("SHA"));
			airports.add(map.get("PEK"));
			airports.add(map.get("SZX"));
			airports.add(map.get("CAN"));
			airports.add(map.get("TAO"));
			airports.add(map.get("CTU"));
			airports.add(map.get("HGH"));
			airports.add(map.get("TSN"));
			airports.add(map.get("XMN"));
			return airports;
		}
		for (Airport airport : map.values()) {
			if (airport.getAirportCode().indexOf(text) > -1 || airport.getAirportName().indexOf(text) > -1 || airport.getCityCode().indexOf(text) > -1 || airport.getCityName().indexOf(text) > -1) {
				airports.add(airport);
				if (airports.size() == 8) {
					return airports;
				}
			}
		}
		return airports;
	}

	/**
	 * 更新机场中国家的英文名
	 * 
	 * @author zhang
	 * @return
	 */
	public CommonResult updateAllFromCache() {
		try {
			List<Airport> airports = this.findAllFromCache();
			for (Airport airport : airports) {
				if(airport.getCountryCode() != null){
					if(airport.getCountryCode().equals("US")){
						airport.setCountryNameEn("America");
					}
					if(airport.getCountryCode().equals("CN")){
						airport.setCountryNameEn("China");
					}
				}
			}
			System.out.println("更新成功！");
			return CommonResult.makeSuccess("更新成功！");
		} catch (Exception e) {
			logger.error("更新机场出错！", e);
		}
		return CommonResult.makeFail("更新机场出错！");
	}

}
